import logging
import threading

from flask import current_app


class MyLogger:
    def __init__(self, name, level=logging.DEBUG, console=True, file=False, filename=None):
        self.logger = current_app.logger
        self.logger.setLevel(level)
        self.console = console
        self.file = file
        self.filename = filename

        if self.console:
            console_handler = logging.StreamHandler()
            console_handler.setLevel(level)
            formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            console_handler.setFormatter(formatter)
            self.logger.addHandler(console_handler)

        if self.file:
            file_handler = logging.FileHandler(filename)
            file_handler.setLevel(level)
            logid_filter = ContextFilter()
            file_handler.addFilter(logid_filter)
            formatter = logging.Formatter(
                "[%(asctime)s][%(logid)s][%(filename)s:%(lineno)d][%(levelname)s] - %(message)s")
            file_handler.setFormatter(formatter)
            self.logger.addHandler(file_handler)

    def debug(self, msg, *args, **kwargs):
        self.logger.debug(msg, *args, **kwargs)

    def info(self, msg, *args, **kwargs):
        self.logger.info(msg, *args, **kwargs)

    def warning(self, msg, *args, **kwargs):
        self.logger.warning(msg, *args, **kwargs)

    def error(self, msg, *args, **kwargs):
        self.logger.error(msg, *args, **kwargs)

    def critical(self, msg, *args, **kwargs):
        self.logger.critical(msg, *args, **kwargs)


thread_local = threading.local()


class ContextFilter(logging.Filter):
    """
    logging Filter
    """

    def filter(self, record):
        """
        threading local 获取logid
        :param record:
        :return:
        """
        log_id = thread_local.logid if hasattr(thread_local, 'logid') else '-'
        record.logid = log_id

        return True
